package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.model.Community;
import com.property.demo.service.CommunityService;
import com.property.demo.util.SortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/communities")
public class CommunityController {

    @Autowired
    private CommunityService communityService;

    @GetMapping
    public ResponseEntity<?> getAllCommunities(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "id,desc") String[] sort) {
        
        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));
            
            Page<Community> communitiesPage;
            if (name != null && !name.isEmpty()) {
                communitiesPage = communityService.findByFilters(name, pageable);
            } else {
                communitiesPage = communityService.findAll(pageable);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", communitiesPage.getContent());
            response.put("currentPage", communitiesPage.getNumber());
            response.put("totalItems", communitiesPage.getTotalElements());
            response.put("totalPages", communitiesPage.getTotalPages());
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(
                new ApiResponse(false, "获取社区列表失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<Community>> getAllCommunitiesNoPage() {
        List<Community> communities = communityService.findAll();
        return new ResponseEntity<>(communities, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Community> getCommunityById(@PathVariable Long id) {
        Community community = communityService.findById(id);
        return new ResponseEntity<>(community, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<ApiResponse> createCommunity(@RequestBody Community community) {
        Community savedCommunity = communityService.save(community);
        return new ResponseEntity<>(
                new ApiResponse(true, "Community created successfully", savedCommunity),
                HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse> updateCommunity(
            @PathVariable Long id, @RequestBody Community communityDetails) {
        Community updatedCommunity = communityService.update(id, communityDetails);
        return new ResponseEntity<>(
                new ApiResponse(true, "Community updated successfully", updatedCommunity),
                HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteCommunity(@PathVariable Long id) {
        communityService.delete(id);
        return new ResponseEntity<>(
                new ApiResponse(true, "Community deleted successfully"),
                HttpStatus.OK);
    }

    @GetMapping("/search")
    public ResponseEntity<List<Community>> searchCommunities(@RequestParam String name) {
        List<Community> communities = communityService.findByNameContaining(name);
        return new ResponseEntity<>(communities, HttpStatus.OK);
    }
    
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        Map<String, Object> statistics = communityService.getStatistics();
        return new ResponseEntity<>(statistics, HttpStatus.OK);
    }
}